import React, {Component, createRef} from 'react';

class Index extends Component {

  state = {
    msg: '',
    age: 19,
    list: Array(100).fill(100)
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    console.log(prevState)
    // console.log(nextProps)
    // console.log(prevState)
    // //根据nextProps和prevState计算出预期的状态改变，返回结果会被送给setState
    // 看到这样的函数声明，应该感受到React的潜台词：老实做一个运算就行，别在这里搞什么别的动作。
    if (!prevState.msg) {
      return {
        msg: nextProps.name
      }
    }
    return null
  }

  componentDidMount() {
    console.log('didmount')
  }

  changeState = () => {
    this.setState({
      list: [
        ...this.state.list,
        1000
      ]
    })
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // console.log(prevProps)
    // console.log(prevState)
    // console.log(snapshot)
    // console.log(this.ulRef.current.scrollHeight)
    // console.log(snapshot - this.ulRef.current.scrollHeight)
    document.documentElement.scrollTop += this.ulRef.current.scrollHeight - snapshot
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log('getsnapshotbeforeupdate')
    console.log(this.ulRef.current.scrollHeight)
    return this.ulRef.current.scrollHeight
  }

  ulRef = createRef()

  render() {
    return (
      <div style={{borderBottom: '20px solid red'}}>
        <button style={{position: 'fixed', top: 0}} onClick={this.changeState}>点击更新</button>
        <ul ref={this.ulRef}>
          {
            this.state.list.map(item => {
              return <li>{item}</li>
            })
          }
        </ul>
      </div>
    );
  }
}

export default Index;
